package conf

import (
	"fmt"
	"sync"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func MySQL() *mySQL {
	return &mySQL{
		// Host:     "127.0.0.1",
		Host: "172.16.1.15",

		Port:     3306,
		DB:       "go15",
		Username: "root",
		Password: "123456",
		Debug:    true,
	}
}

type mySQL struct {
	Host     string `json:"host,omitempty" yaml:"host"`
	Port     int    `json:"port,omitempty" yaml:"port"`
	DB       string `json:"db,omitempty" yaml:"db"`
	Username string `json:"username,omitempty" yaml:"username"`
	Password string `json:"password,omitempty" yaml:"password"`
	Debug    bool   `json:"debug,omitempty" yaml:"debug"`

	db   *gorm.DB
	lock sync.Mutex
}

func (m *mySQL) dsn() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		m.Username,
		m.Password,
		m.Host,
		m.Port,
		m.DB,
	)
}

func (m *mySQL) GetDB() *gorm.DB {
	m.lock.Lock()

	defer m.lock.Unlock()

	if m.db == nil {
		db, err := gorm.Open(mysql.Open(m.dsn()), &gorm.Config{})
		if err != nil {

			panic(err)
		}
		m.db = db

		if m.Debug {
			m.db = db.Debug()
		}
	}
	return m.db
}
